package com.ebeijia.common;

import com.ebeijia.util.LoggerUtil;
import com.ebeijia.util.PropertiesUtils;

import java.io.*;

/**
 * Created by YPJ on 2016/6/24.
 */
public class FileOperation {
	private static String filenameTemp;

	/**
	 * 创建文件
	 * 
	 * @param name
	 * @return
	 */
	public static String createFile(String name) throws Exception {
		String filePath = null;
		try {
			String path = PropertiesUtils.getProperties("txt.upload.path");
			filenameTemp = path + name + ".txt";
			File fileName = new File(filenameTemp);
			if (!fileName.exists()) {
				fileName.createNewFile();
				filePath = fileName.toString();
			}

		} catch (Exception e) {
			LoggerUtil.error(e.getMessage(), e);
		}
		return filePath;
	}

	/**
	 * 读TXT文件内容
	 * 
	 * @param path
	 * @return
	 */
	public static String readTxtFile(String path) throws Exception {
		StringBuffer result = new StringBuffer();
		BufferedReader bufferedReader = null;
		try {
			bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(path),"UTF-8"));
			try {
				String read = "";
				while ((read = bufferedReader.readLine()) != null) {
					result.append(read);
				}
			} catch (Exception e) {
				LoggerUtil.error(e.getMessage(), e);
			}
		} catch (Exception e) {
			LoggerUtil.error(e.getMessage(), e);
		} finally {
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (Exception e) {
					LoggerUtil.error(e.getMessage(), e);
				}
			}
			
		}
		return result.toString();
	}

	public static boolean writeTxtFile(String content, String path)
			throws Exception {
		BufferedWriter bw=null;
		boolean flag = false;
		FileOutputStream o = null;
		try {
			bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path),"UTF-8"));
			bw.write(content);
			bw.flush();
			flag = true;
		} catch (Exception e) {
			LoggerUtil.error(e.getMessage(), e);
		} finally {
			if (bw != null) {
				try {
					bw.close();
				} catch (Exception e) {
					LoggerUtil.error(e.getMessage(), e);
				}
			}
		}
		return flag;
	}

	public static void contentToTxt(String filePath, String content) {
		String oldStr = new String(); // 原有txt内容
		String newStr = new String();// 内容更新
		BufferedWriter output = null;
		try {
			File f = new File(filePath);
			if (!f.exists()) {
				LoggerUtil.info("文件不存在");
				f.createNewFile();// 不存在则创建
			}
			BufferedReader input = new BufferedReader(new FileReader(f));

			while ((oldStr = input.readLine()) != null) {
				newStr += oldStr;
			}
			input.close();
			newStr += content;

			output = new BufferedWriter(new FileWriter(f));
			output.write(newStr);
			output.flush();

		} catch (Exception e) {
			LoggerUtil.error(e.getMessage(), e);

		} finally {
			if (output != null) {
				try {
					output.close();
				} catch (IOException e) {
					LoggerUtil.error(e.getMessage(), e);
				}
			}
		}
	}
}
